/*
 * @Author: Jhinwins 
 * @Date: 2018-03-17 13:13:02 
 * @Last Modified by: Jhinwins
 * @Last Modified time: 2018-04-13 22:44:28
 */
//注意，这个地方不能使用PureComponent，否则会出现数据更新但是页面不更新的问题
import React, { Component } from "react";
import {
  Row,
  Col,
  Divider,
  Radio,
  InputNumber,
  Button,
  Icon,
  Tabs,
  Rate,
  Input,
  Avatar,
  notification
} from "antd";
import Req from "../common/Req";

export default class DetailPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      specifications: {},
      bigPic: null,
      evaluates: [],
      commodity: {},
      count: 1,
      time: 1
    };
  }

  componentWillMount() {
    let { productid } = this.props.location.state;
    //加载商品数据
    Req(
      "http://localhost:8080/products/product?productid=" + productid,
      {},
      this.props.history,
      resp => {
        this.setState({ commodity: resp.data });
      }
    );

    //加载评论
    Req(
      "http://localhost:8080/evaluate?productid=" + productid,
      {},
      this.props.history,
      resp => {
        this.setState({ evaluates: resp.data });
      }
    );
  }
  render() {
    console.log(this.state.commodity);
    return (
      <div>
        <Row
          style={{
            backgroundRepeat: "no-repeat",
            backgroundSize: "cover",
            backgroundImage:
              'url("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3080292925,4188312909&fm=27&gp=0.jpg")'
          }}
        >
          <Col span={4} offset={18}>
            <Input.Search
              style={{ marginTop: 30, marginBottom: 30 }}
              placeholder="输入您想购买的商品"
              onSearch={value => console.log(value)}
            />
          </Col>
        </Row>
        <Row style={{ background: "#ffffff", marginTop: 10, padding: 15 }}>
          <Col span={10}>
            <div>
              <img
                style={{ width: "100%", height: 280 }}
                alt=""
                src={
                  this.state.bigPic
                    ? this.state.bigPic
                    : this.state.commodity.pics && this.state.commodity.pics[0]
                      ? this.state.commodity.pics[0].imgUrl
                      : ""
                }
              />
              <Row
                type="flex"
                justify="center"
                gutter={10}
                style={{ marginTop: 5 }}
              >
                {this.state.commodity.pics ? (
                  this.state.commodity.pics.map((item, index) => (
                    <Col key={index} span={4}>
                      <img
                        onClick={() => this.setState({ bigPic: item.imgUrl })}
                        style={{ width: "100%", height: "100%" }}
                        alt=""
                        src={item.imgUrl}
                      />
                    </Col>
                  ))
                ) : (
                  <div>暂无图片</div>
                )}
              </Row>
            </div>
          </Col>
          <Col span={14}>
            <div style={{ marginLeft: 50 }}>
              <h1>{this.state.commodity.name}</h1>
              <h4>{this.state.commodity.desc}</h4>
              <div
                style={{
                  paddingTop: 20,
                  paddingLeft: 10
                }}
              >
                <h2 style={{ color: "#FF4949" }}>
                  $ {this.state.commodity.price}
                </h2>
              </div>
              <Divider />
              <div>
                {this.state.commodity.specifications ? (
                  this.state.commodity.specifications.map((item, index) => (
                    <div key={index}>
                      <span>{item.name}：</span>
                      <Radio.Group
                        size="small"
                        value={this.state.specifications[item.specId]}
                        onChange={e => {
                          let new_specifications = this.state.specifications;
                          new_specifications[item.specId] = e.target.value;
                          this.setState({ specifications: new_specifications });
                        }}
                      >
                        {item.opts.map((opt, index) => (
                          <Radio.Button
                            key={index}
                            style={{ marginBottom: 10 }}
                            value={opt.specValueId}
                          >
                            {opt.name}
                          </Radio.Button>
                        ))}
                      </Radio.Group>
                    </div>
                  ))
                ) : (
                  <div>暂无规格</div>
                )}

                <div style={{ marginBottom: 10 }}>
                  <span>数量：</span>
                  <InputNumber
                    size="small"
                    min={1}
                    max={100}
                    defaultValue={1}
                    onChange={e => this.setState({ count: e })}
                  />
                  <span style={{ marginLeft: 20 }}>租期：</span>
                  <InputNumber
                    size="small"
                    min={1}
                    max={100}
                    defaultValue={1}
                    onChange={e => this.setState({ time: e })}
                  />
                  <span>天</span>
                </div>
              </div>
              <Divider />
              <div>
                <Button
                  type="primary"
                  size="large"
                  onClick={() => {
                    let params = {
                      specifications: this.state.specifications,
                      productId: this.state.commodity.id,
                      tenancy: this.state.time,
                      count: this.state.count
                    };
                    Req(
                      "http://localhost:8080/products/addtocart",
                      {
                        method: "POST",
                        headers: {
                          "Content-type": "application/json"
                        },
                        body: JSON.stringify(params)
                      },
                      this.props.history,
                      resp => {
                        if (resp.code !== 100) {
                          notification["error"]({
                            message: "添加购物车失败",
                            description: "请求错误"
                          });
                          return;
                        }

                        if (resp.data.status === "SUCCESS") {
                          notification["success"]({
                            message: "Bingo",
                            description: "添加购物车成功"
                          });
                        } else {
                          notification["error"]({
                            message: "添加购物车失败",
                            description: "库存不足"
                          });
                        }
                      }
                    );
                  }}
                >
                  <Icon type="shopping-cart" />加入购物车
                </Button>
              </div>
            </div>
          </Col>
        </Row>
        {/**产品介绍*/}
        <Row style={{ marginTop: 15, background: "#ffffff" }}>
          <Col span={24}>
            <Divider />
            <Tabs
              tabPosition="right"
              defaultActiveKey="1"
              onChange={e => console.log(e)}
            >
              <Tabs.TabPane tab="商品详情" key="1">
                <ProductIntroduce
                  introduces={this.state.commodity.introduces}
                />
              </Tabs.TabPane>
              <Tabs.TabPane tab="用户评价" key="2">
                <Evaluate evaluates={this.state.evaluates} />
              </Tabs.TabPane>
            </Tabs>
            <Divider />
          </Col>
        </Row>
      </div>
    );
  }
}

class ProductIntroduce extends Component {
  render() {
    return (
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center"
        }}
      >
        {this.props.introduces ? (
          <img src={this.props.introduces.imgUrl} alt="" />
        ) : (
          <div>暂无介绍</div>
        )}
      </div>
    );
  }
}

class Evaluate extends Component {
  render() {
    return (
      <div>
        <div style={{ textAlign: "center" }}>
          <Rate disabled allowHalf defaultValue={2.5} />
        </div>
        <Divider />
        <h3>用户评论：</h3>
        <div>
          {this.props.evaluates.map((item, index) => (
            <EvaluateItem key={index} evaluateInfo={item} />
          ))}
        </div>
      </div>
    );
  }
}

class EvaluateItem extends Component {
  render() {
    const { evaluateInfo } = this.props;
    return (
      <div>
        <Row>
          <Col span={8}>
            <div style={{ textAlign: "center" }}>
              <Avatar size="large" icon="user" />
              <div>{evaluateInfo.username}</div>
            </div>
          </Col>
          <Col span={16}>
            <div>
              <div>
                <Rate disabled allowHalf defaultValue={evaluateInfo.rate} />
              </div>
              <div>{evaluateInfo.content}</div>
            </div>
            <div style={{ textAlign: "right" }}>{evaluateInfo.time}</div>
          </Col>
        </Row>
        <Divider />
      </div>
    );
  }
}
